<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('指标名称')" prop="name">
            <el-input v-model="form.name" :placeholder="$t('指标名称')" maxlength="20" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('指标的字段类型')" prop="type">
            <el-select v-model="form.type" :placeholder="$t('请选择')">
              <el-option
                v-for="dict in typeOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('分类')" prop="group">
            <el-select v-model="form.group" :placeholder="$t('请选择')">
              <el-option
                v-for="dict in groupOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!--        <el-col :span="12">-->
        <!--          <el-form-item :label="$t('颜色设置')" prop="color">-->
        <!--            <el-color-picker-->
        <!--              v-model="form.color"-->
        <!--              show-alpha-->
        <!--              :predefine="predefineColors"-->
        <!--            />-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <el-col :span="24">
          <el-form-item :label="$t('备注信息')" prop="remark">
            <el-input v-model="form.remark" type="textarea" :rows="8" :placeholder="$t('请选择')" maxlength="100" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="indicatorsSql">
            <span slot="label">
              {{ $t('查询指标的Sql') }}
              <el-tooltip placement="top">
                <div slot="content">
                  {{ $t('内置参数') }}<br>
                  ${currentTime}:{{ $t('当前时间') }}<br>
                  ${currentUser}:{{ $t('当前用户') }}
                </div>
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <textarea ref="indicatorsSql" v-model="form.indicatorsSql" class="codesql" style="height:200px;width:600px;" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="detailsSql">
            <span slot="label">
              {{ $t('查询详情的SQL') }}
              <el-tooltip placement="top">
                <div slot="content">
                  {{ $t('内置参数') }}<br>
                  ${currentTime}:{{ $t('当前时间') }}<br>
                  ${currentUser}:{{ $t('当前用户') }}
                </div>
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <textarea ref="detailsSql" v-model="form.detailsSql" class="codesql" style="height:200px;width:600px;" />
          </el-form-item>
        </el-col>
      </el-row>
      <div style="display: flex;align-items: baseline;margin: 10px 0;">
        <div class="area-header" style="flex:1;margin:0;">
          <span class="area-header-title">{{ $t('详情字段配置') }}</span>
        </div>
        <el-button v-if="form.detailsSql" type="primary" plain size="small" icon="el-icon-refresh" @click="refreshColumn">{{ $t('刷新') }}</el-button>
      </div>
      <el-table :data="form.fieldList" border>
        <el-table-column :label="$t('字段名称')" align="center" prop="fieldName" />
        <el-table-column :label="$t('字段描述')" align="center" prop="fieldRemark">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('字段描述') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'fieldList.' + scope.$index + '.fieldRemark'">
              <el-input v-model="scope.row.fieldRemark" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('字段类型')" align="center" prop="type" width="110">
          <template slot-scope="scope">
            <el-form-item :prop="'fieldList.' + scope.$index + '.type'">
              <el-select v-model="scope.row.type" :placeholder="$t('请选择')" @change="updateFormatValue(scope.row)">
                <el-option
                  v-for="dict in typeOptions"
                  :key="dict.dictValue"
                  :label="$t(dict.dictLabel)"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('格式化')" align="center">
          <template slot-scope="scope">
            <el-form-item :prop="'fieldList.' + scope.$index + '.type'">
              <el-input v-if="scope.row.type === 'RQ' || scope.row.type === 'JE' || scope.row.type === 'BL'" v-model="scope.row.format" />
              <el-select v-if="scope.row.type === 'ZD'" v-model="scope.row.format" value="" clearable filterable :placeholder="$t('请选择')" style="width: 100%">
                <el-option
                  v-for="dict in dictOptions"
                  :key="dict.dictType"
                  :label="$t(dict.dictName)"
                  :value="dict.dictType"
                >
                  <span style="float: left">{{ $t(dict.dictName) }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ dict.dictType }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('是否展示')" align="center" prop="isShow" width="100">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('是否展示') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'fieldList.' + scope.$index + '.isShow'">
              <el-switch
                v-model="scope.row.isShow"
                :active-value="yesNoOptions[0].dictValue"
                :inactive-value="yesNoOptions[1].dictValue"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('打开链接的方式')" align="center" prop="linkType">
          <template slot-scope="scope">
            <el-select v-model="scope.row.linkType" value="" clearable filterable placeholder="请选择" style="width: 100%">
              <el-option
                v-for="dict in openLinkTypeOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column :label="$t('打开链接的地址')" align="center" prop="linkAddress">
          <template slot-scope="scope">
            <el-form-item :prop="'fieldList.' + scope.$index + '.linkAddress'">
              <el-input v-show="scope.row.linkType !== 'BDK' && scope.row.linkType !== '' && scope.row.linkType !== null" v-model="scope.row.linkAddress" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('打开链接时携带的参数')" align="center" prop="linkParameter">
          <template slot-scope="scope">
            <el-form-item :prop="'fieldList.' + scope.$index + '.linkParameter'">
              <el-input v-show="scope.row.linkType !== 'BDK' && scope.row.linkType !== '' && scope.row.linkType !== null" v-model="scope.row.linkParameter" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('是否数据穿透')" prop="drillDown" align="center">
          <template slot-scope="scope">
            <el-form-item :prop="'fieldList.' + scope.$index + '.drillDown'">
              <el-select v-model="scope.row.drillDown" value="" clearable filterable :placeholder="$t('请选择')" style="width: 100%">
                <el-option
                  v-for="dict in yesNoOptions"
                  :key="dict.dictValue"
                  :label="$t(dict.dictLabel)"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('数据穿透配置')" align="center">
          <template slot-scope="scope">
            <el-button v-if="scope.row.drillDown === 'Y'" type="primary" size="small" @click="drillDownConfigure(scope.row, scope.$index)">{{ $t('数据穿透配置') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <SaveBtn has-permi="system:indicators" />
    </div>
    <el-dialog :visible.sync="drillDownOpen" :title="$t('数据穿透配置')" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <home-indicators-drill-down-form ref="drillDownForm" @close="drillDownClose" />
    </el-dialog>
  </div>
</template>

<script>
    import { getColumnBySql } from '@/api/system/search/searchSqlBase'
    import { saveHomeIndicators, getHomeIndicators } from '@/api/system/home/homeIndicators'
    // import { executeSQL } from '@/api/system/home/homeIndicatorsField'
    import { optionselect as getDictOptionselect } from '@/api/system/dict/type'
    import 'codemirror/theme/ambiance.css'
    import 'codemirror/lib/codemirror.css'
    import 'codemirror/addon/hint/show-hint.css'
    import HomeIndicatorsDrillDownForm from '@/views/system/home/homeIndicatorsDrillDownForm'

    const CodeMirror = require('codemirror/lib/codemirror')
    require('codemirror/addon/edit/matchbrackets')
    require('codemirror/addon/selection/active-line')
    require('codemirror/mode/sql/sql')
    require('codemirror/addon/hint/show-hint')
    require('codemirror/addon/hint/sql-hint')
    export default {
        name: 'CodeMirror',
      components: { HomeIndicatorsDrillDownForm },
      data() {
            return {
                loading: false,
                // 指标的字段类型字典
                typeOptions: [], // 表单参数
                // 分类字典数据
                groupOptions: [],
                // 系统是否字典数据
                yesNoOptions: [],
                // 页面打开方式
                openLinkTypeOptions: [],
                // 指标查询脚本控件
                indicatorsSqlEditor: {},
                // 查询详情脚本的控件
                detailsSqlEditor: {},
                // 字典信息
                dictOptions: [],
                fieldListIndex: undefined,
                // predefineColors: [
                //   '#ff4500',
                //   '#ff8c00',
                //   '#ffd700',
                //   '#90ee90',
                //   '#00ced1',
                //   '#1e90ff',
                //   '#c71585',
                //   'rgba(255, 69, 0, 0.68)',
                //   'rgb(255, 120, 0)',
                //   'hsv(51, 100, 98)',
                //   'hsva(120, 40, 94, 0.5)',
                //   'hsl(181, 100%, 37%)',
                //   'hsla(209, 100%, 56%, 0.73)',
                //   '#c7158577'
                // ],
                // 颜色
                // colorList: [{ color: '#5893FF' }, { color: '#32B4FF' }, { color: '#FDB235' }, { color: '#FE7A85' }, { color: '#8F8AF1' }],
                form: {},
                // 表单校验
                rules: {
                  type: [
                    { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
                  ],
                  name: [
                    { required: true, message: this.$t('必填信息'), trigger: ['blur'] }
                  ],
                  // color: [
                  //   { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
                  // ],
                  group: [
                    { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
                  ]
                },
              drillDownOpen: false
            }
        },
        created() {
            this.getDicts('search_field_type').then(response => {
                this.typeOptions = response.data
            })
            this.getDicts('home_group').then(response => {
              this.groupOptions = response.data
            })
            this.getDicts('sys_yes_no').then(response => {
              this.yesNoOptions = response.data
            })
            //  新页面打开方式
            this.getDicts('open_link_type').then(response => {
              this.openLinkTypeOptions = response.data
            })
            /** 查询字典下拉列表 */
            getDictOptionselect().then(response => {
              this.dictOptions = response.data
            })
        },
        mounted() {
          const mime = 'text/x-mariadb'
          // let theme = 'ambiance'//设置主题，不设置的会使用默认主题
          this.indicatorsSqlEditor = CodeMirror.fromTextArea(this.$refs.indicatorsSql, {
            mode: mime, // 选择对应代码编辑器的语言，我这边选的是数据库，根据个人情况自行设置即可
            indentWithTabs: true,
            smartIndent: true,
            lineNumbers: true,
            matchBrackets: true,
            // theme: theme,
            // autofocus: true,
            extraKeys: { 'Ctrl': 'autocomplete' }, // 自定义快捷键
            hintOptions: { // 自定义提示选项
              tables: {
                users: ['name', 'score', 'birthDate'],
                countries: ['name', 'population', 'size']
              }
            }
          })
          this.indicatorsSqlEditor.on('cursorActivity', function() {
            if (this !== null) {
              this.indicatorsSqlEditor.showHint()
            }
          })

          // let theme = 'ambiance'//设置主题，不设置的会使用默认主题
          this.detailsSqlEditor = CodeMirror.fromTextArea(this.$refs.detailsSql, {
            mode: mime, // 选择对应代码编辑器的语言，我这边选的是数据库，根据个人情况自行设置即可
            indentWithTabs: true,
            smartIndent: true,
            lineNumbers: true,
            matchBrackets: true,
            // theme: theme,
            // autofocus: true,
            extraKeys: { 'Ctrl': 'autocomplete' }, // 自定义快捷键
            hintOptions: { // 自定义提示选项
              tables: {
                users: ['name', 'score', 'birthDate'],
                countries: ['name', 'population', 'size']
              }
            }
          })
          this.detailsSqlEditor.on('cursorActivity', function() {
            if (this !== null) {
              this.detailsSqlEditor.showHint()
            }
          })
        },
        methods: {
            // 初始化数据
            init(data) {
                this.loading = true
                if (data != null && data.id !== undefined) {
                    getHomeIndicators(data.id).then(response => {
                        this.form = response.data
                        this.form.fieldList = response.data.fieldList == null ? [] : response.data.fieldList

                        this.loading = false
                        this.indicatorsSqlEditor.setValue(this.form.indicatorsSql !== null ? this.form.indicatorsSql : '')
                        this.detailsSqlEditor.setValue(this.form.detailsSql !== null ? this.form.detailsSql : '')
                    })
                } else {
                    this.reset()
                    this.loading = false
                }
            },
            // 表单重置
            reset() {
                this.form = {
                id: undefined,
                name: undefined,
                type: undefined,
                indicatorsSql: undefined,
                detailsSql: undefined,
                createBy: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateTime: undefined,
                delFlag: undefined
                // color: undefined
                }
                this.indicatorsSqlEditor.setValue('')
                this.detailsSqlEditor.setValue('')
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                this.$parent.$parent.formOpen = false
                // 刷新list页面
                this.$parent.$parent.getList()
            },
            /** 提交按钮 */
            submitForm: function() {
                this.form.indicatorsSql = this.indicatorsSqlEditor.getValue()
                this.form.detailsSql = this.detailsSqlEditor.getValue()
                this.$refs['form'].validate(valid => {
                    if (valid) {
                      this.loading = true
                        saveHomeIndicators(this.form).then(response => {
                            if (response.code === 200) {
                                this.msgSuccess(this.$t('保存成功'))
                                this.closeForm()
                            } else {
                                this.msgError(response.msg)
                              this.loading = false
                            }
                        }).catch(() => {
                          this.loading = false
                        })
                    } else {
                      this.locationError(document)
                    }
                })
           },
            // 点击刷新按钮执行查询详情SQL 获取表信息
            refreshColumn() {
              this.form.detailsSql = this.detailsSqlEditor.getValue()
              var data = {}
              data.searchSql = this.form.detailsSql
              getColumnBySql(data).then(response => {
                this.$forceUpdate()

                // 保存之前配置的数据
                var fieldTempMap = {}
                for (var j = 0; j < this.form.fieldList.length; j++) {
                  var filed = this.form.fieldList[j]
                  fieldTempMap[filed.fieldName] = filed
                }
                var fieldList = []
                for (var i = 0; i < response.data.length; i++) {
                  var field = {}
                  if (fieldTempMap[response.data[i]] !== null && fieldTempMap[response.data[i]] !== undefined) {
                    field = fieldTempMap[response.data[i]]
                    field.sort = (i + 1) * 10
                  } else {
                    field.fieldName = response.data[i]
                    field.fieldRemark = response.data[i]
                    field.type = 'WB'
                    field.isShow = 'Y'
                    field.sort = (i + 1) * 10
                    field.width = 200
                  }
                  fieldList.push(field)
                }
                this.form.fieldList = fieldList
                return this.msgSuccess(this.$t('操作成功'))
              }).catch(function() {})
            },
            // 设置格式化字段默认值
            updateFormatValue: function(row) {
              if (row.type === 'JE' || row.type === 'BL') {
                row.format = '###,###.####'
              } else if (row.type === 'RQ') {
                row.format = 'yyyy-MM-dd'
              }
            },
            drillDownConfigure(row, index) {
              this.drillDownOpen = true
              this.fieldListIndex = index
              this.$nextTick(() => {
                this.$refs.drillDownForm.init(row.homeIndicatorsDrillDown)
              })
            },
            drillDownClose(data) {
              this.drillDownOpen = false
              console.log(this.fieldListIndex)
              if (data) {
                this.$set(this.form.fieldList[this.fieldListIndex], 'homeIndicatorsDrillDown', data)
              }
            }
        }

    }
</script>

<style scoped>
  .colorChoose li.active {
    position: relative;
  }

  .colorChoose li.active:after {
    position: absolute;
    content: '';
    display: block;
    top: 15px;
    right: 18px;
    width: 6px;
    height: 11px;
    border-style: solid;
    border-color: white;
    border-width: 0 2px 2px 0;
    -webkit-transform: rotateZ(45deg);
    transform: rotateZ(45deg);
  }

  .colorChoose li {
    float: left;
    cursor: pointer;

  }

  .colorChoose li span {
    height: 24px;
    width: 24px;
    display: block;
    margin: 10px;
  }
  .codesql {
    font-size: 11pt;
    font-family: Consolas, Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace, serif;
  }
</style>
